using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using JGSY.CMS.LowCode.Platform.Domain.Entities;
using JGSY.CMS.LowCode.Platform.Domain.Interfaces;
using JGSY.CMS.LowCode.Platform.Infrastructure.CmsDbContext;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Repositories
{
    /// <summary>
    /// 表单仓储实现
    /// 提供表单数据访问操作的完整实现，包括表单管理和统计功能
    /// </summary>
    public class FormRepository : Repository<Form>, IFormRepository
    {
        public FormRepository(LowCodeDbContext context) : base(context)
        {
        }

        /// <summary>
        /// 获取所有表单记录
        /// </summary>
        async Task<IEnumerable<Form>> IFormRepository.GetAllAsync()
        {
            return await _context.Forms
                .Include(f => f.Fields)
                .Include(f => f.Creator)
                .OrderByDescending(f => f.CreatedAt)
                .ToListAsync();
        }

        /// <summary>
        /// 根据ID获取表单记录
        /// </summary>
        public async Task<Form?> GetByIdAsync(long id)
        {
            return await _context.Forms
                .Include(f => f.Fields)
                .Include(f => f.Submissions)
                .Include(f => f.Creator)
                .FirstOrDefaultAsync(f => f.Id == id);
        }

        /// <summary>
        /// 根据标识符获取表单记录
        /// </summary>
        public async Task<Form?> GetByIdentifierAsync(string identifier)
        {
            return await _context.Forms
                .Include(f => f.Fields)
                .Include(f => f.Creator)
                .FirstOrDefaultAsync(f => f.Name == identifier && f.Status == 1);
        }

        /// <summary>
        /// 获取活跃表单
        /// </summary>
        public async Task<IEnumerable<Form>> GetActiveFormsAsync()
        {
            return await _context.Forms
                .Include(f => f.Fields)
                .Include(f => f.Creator)
                .Where(f => f.Status == 1)
                .OrderByDescending(f => f.CreatedAt)
                .ToListAsync();
        }

        /// <summary>
        /// 获取时间范围内的活跃表单
        /// </summary>
        public async Task<IEnumerable<Form>> GetActiveFormsInTimeRangeAsync(DateTime? startTime, DateTime? endTime)
        {
            var query = _context.Forms
                .Include(f => f.Fields)
                .Include(f => f.Creator)
                .Where(f => f.Status == 1)
                .AsQueryable();

            if (startTime.HasValue)
                query = query.Where(f => f.CreatedAt >= startTime.Value);

            if (endTime.HasValue)
                query = query.Where(f => f.CreatedAt <= endTime.Value);

            return await query
                .OrderByDescending(f => f.CreatedAt)
                .ToListAsync();
        }

        /// <summary>
        /// 分页获取表单列表
        /// </summary>
        public async Task<(IEnumerable<Form> Items, int TotalCount)> GetPagedAsync(int pageIndex, int pageSize, string? keyword = null, byte? status = null)
        {
            var query = _context.Forms
                .Include(f => f.Fields)
                .Include(f => f.Creator)
                .AsQueryable();

            if (!string.IsNullOrWhiteSpace(keyword))
            {
                query = query.Where(f => f.Name.Contains(keyword) ||
                                        (f.Description != null && f.Description.Contains(keyword)));
            }

            if (status.HasValue)
            {
                query = query.Where(f => f.Status == status.Value);
            }

            var total = await query.CountAsync();

            var items = await query
                .OrderByDescending(f => f.CreatedAt)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToListAsync();

            return (items, total);
        }

        /// <summary>
        /// 添加新表单
        /// </summary>
        async Task IFormRepository.AddAsync(Form entity)
        {
            entity.CreatedAt = DateTime.UtcNow;
            entity.UpdatedAt = DateTime.UtcNow;
            await _context.Forms.AddAsync(entity);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 更新表单信息
        /// </summary>
        public override async Task<Form> UpdateAsync(Form entity)
        {
            entity.UpdatedAt = DateTime.UtcNow;
            _context.Forms.Update(entity);
            await _context.SaveChangesAsync();
            return entity;
        }

        // 显式接口实现：接口为 Task 版本
        async Task IFormRepository.UpdateAsync(Form entity)
        {
            _ = await UpdateAsync(entity);
        }

        /// <summary>
        /// 删除表单
        /// </summary>
        public async Task DeleteAsync(long id)
        {
            var entity = await _context.Forms.FindAsync(id);
            if (entity != null)
            {
                _context.Forms.Remove(entity);
                await _context.SaveChangesAsync();
            }
        }

        /// <summary>
        /// 批量删除表单
        /// </summary>
        public async Task<int> BatchDeleteAsync(IEnumerable<long> ids)
        {
            var forms = await _context.Forms
                .Where(f => ids.Contains(f.Id))
                .ToListAsync();

            _context.Forms.RemoveRange(forms);
            return await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 检查表单标识符是否存在
        /// </summary>
        public async Task<bool> IdentifierExistsAsync(string identifier, long? excludeId = null)
        {
            var query = _context.Forms.Where(f => f.Name == identifier);
            
            if (excludeId.HasValue)
                query = query.Where(f => f.Id != excludeId.Value);

            return await query.AnyAsync();
        }

        /// <summary>
        /// 增加表单提交数量
        /// </summary>
        public async Task<bool> IncrementSubmissionCountAsync(long id)
        {
            var form = await _context.Forms.FindAsync(id);
            if (form != null)
            {
                form.SubmissionCount++;
                form.UpdatedAt = DateTime.UtcNow;
                await _context.SaveChangesAsync();
                return true;
            }
            return false;
        }

        /// <summary>
        /// 获取表单统计信息
        /// </summary>
        public async Task<object> GetFormStatisticsAsync(long id)
        {
            var form = await _context.Forms
                .Include(f => f.Submissions)
                .FirstOrDefaultAsync(f => f.Id == id);

            if (form == null)
                return new { };

            var totalSubmissions = form.Submissions.Count;
            var todaySubmissions = form.Submissions.Count(s => s.SubmitTime.Date == DateTime.UtcNow.Date);
            var weekSubmissions = form.Submissions.Count(s => s.SubmitTime >= DateTime.UtcNow.AddDays(-7));
            var monthSubmissions = form.Submissions.Count(s => s.SubmitTime >= DateTime.UtcNow.AddDays(-30));

            return new
            {
                TotalSubmissions = totalSubmissions,
                TodaySubmissions = todaySubmissions,
                WeekSubmissions = weekSubmissions,
                MonthSubmissions = monthSubmissions,
                LastSubmissionAt = form.Submissions.OrderByDescending(s => s.SubmitTime).FirstOrDefault()?.SubmitTime
            };
        }
    }
}
